<template>
  <el-upload
    ref="upload"
    class="common-upload"
    :action="uploadOptionsFn().url"
    :headers="uploadOptionsFn().headers"
    :data="uploadOptionsFn().moduleName"
    v-bind="$attrs"
    :on-error="uploadError"
    :on-success="uploadSuccess"
    :show-file-list="false"
    :before-upload="myBeforeUploadFn"
    element-loading-text="上传中"
    v-loading="uploading"
  >
    <slot>
      <div slot="tip" class="el-upload__tip" v-if="$attrs.tip">{{ $attrs.tip }}</div>
    </slot>
  </el-upload>
</template>

<script>
import { uploadOptionsFn } from '@/utils'

export default {
  props: {
    beforeUpload: Function
  },
  data() {
    return {
      // uploadOptions
      uploading: false
    }
  },
  computed: {},
  created() {},
  mounted() {},
  methods: {
    uploadOptionsFn,
    // 若返回 false 或者返回 Promise 且被 reject，则停止上传
    myBeforeUploadFn(file) {
      this.uploading = true
      if (this.beforeUpload) {
        const before = this.beforeUpload(file)
        if (before && before.then) {
          before.catch((err) => {
            console.log(' err: ', err)
            this.uploading = false
          })
        } else if (before === false) {
          this.uploading = false
        }
        return before
      }
      return true
    },
    uploadSuccess(response) {
      this.uploading = false
      // eslint-disable-next-line eqeqeq
      if (response.code == '00') {
        const fileUrl = response.data.fileUrl
        this.$emit('insertImage', fileUrl)
        this.$emit('success', response.data)
      } else if (response.code) {
        this.$message.error('上传失败: ' + response.msg)
        this.$refs.upload.handleRemove(file, null) // 删除
      } else {
        this.$message.error('上传失败')
        this.$refs.upload.handleRemove(file, null) // 删除
      }
    },
    uploadError(err, file, fileList) {
      this.uploading = false
      this.$attrs['on-error'] && this.$attrs['on-error'](err, file, fileList)
      return this.$message.error('上传失败')
    }
  }
}
</script>
